<template>
	<van-button
		:icon="isCollected ? 'star' : 'star-o'"
		:class="{ collected: isCollected }"
		@click="onCollect"
	></van-button>
</template>

<script>
import { addCollect, deleteCollect } from '@/api/articles'
export default {
	data() {
		return {
			// 点击按钮时的加载效果
			loading: false,
		}
	},
  model:{
      prop:'isCollected',
      event:'updateCollect'
  },
	props: {
		isCollected: {
			type: Boolean,
			requiread: true,
		},
		articleId: {
			type: [Number, String, Object],
			required: true,
		},
	},
	methods: {
		async onCollect() {
      	// 先判断有没有登录
			if (!this.$store.state.user) return this.$toast('请登录')
			this.loading = true
			try {
				if (this.isCollected) {
					// 收藏，取消收藏
					await deleteCollect(this.articleId)
				} else {
					// 未收藏，添加收藏
					await addCollect(this.articleId)
				}
				// 更新视图
				this.$emit('updateCollect', !this.isCollected)
         this.$toast.success(!this.value ? '收藏成功' : '取消收藏')
      
			} catch (err) {
				console.log(err)
				this.$toast.fail('操作失败')
			}
			this.loading = false
		},
	},
}
</script>

<style scoped lang="less">
.collected {
	.van-icon {
		color: #ffa500;
	}
}
</style>
